package com.gingko.duominuo.viewmodel

import androidx.hilt.Assisted
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.gingko.duominuo.data.Resource
import com.gingko.duominuo.data.asResource
import com.gingko.duominuo.data.model.CreateTaskVo
import com.gingko.duominuo.data.model.TaskFilterVo
import com.gingko.duominuo.data.model.TaskVo
import com.gingko.duominuo.data.model.WorkOrderDetailVo
import com.gingko.duominuo.data.request.CreateTaskReqVo
import com.gingko.duominuo.data.request.OrderReqVo
import com.gingko.duominuo.data.request.TaskReqVo
import com.gingko.duominuo.data.source.repository.GinkgoRepository

class TaskViewModel@ViewModelInject constructor(
    private val ginkgoRepository: GinkgoRepository,
    @Assisted
    val state: SavedStateHandle
) : BaseViewModel() {

    private val _taskLiveData = MutableLiveData<Resource<List<TaskVo>>>()
    val taskLiveData: LiveData<Resource<List<TaskVo>>> = _taskLiveData
    private val _workOrderDetailLiveData = MutableLiveData<Resource<WorkOrderDetailVo>>()
    val workOrderDetailLiveData: LiveData<Resource<WorkOrderDetailVo>> = _workOrderDetailLiveData
    private val _createTaskOrderLiveData = MutableLiveData<Resource<CreateTaskVo>>()
    val createTaskOrderLiveData: LiveData<Resource<CreateTaskVo>> = _createTaskOrderLiveData
    private val _countdownLiveData = MutableLiveData<Long>()
    private val _taskFilterLiveData = MutableLiveData<Resource<TaskFilterVo>>()
    val taskFilterLiveData: LiveData<Resource<TaskFilterVo>> = _taskFilterLiveData
    var noTaskOrder: Boolean = true


    fun getTaskFilter() {
        launchOnUI(
            task = {
                _taskFilterLiveData.value = Resource.Success(ginkgoRepository.getTaskFilter())
            },
            onFailure = {
                _taskFilterLiveData.value = Resource.Error(it)
            }
        )
    }

    fun getTasks(taskReqVo: TaskReqVo) {
        launchOnUI(
            task = {
                val result = ginkgoRepository.getWorkOrder(OrderReqVo(status = 0))
                noTaskOrder = result.data?.list_order.isNullOrEmpty()
                _taskLiveData.value = ginkgoRepository.getTasks(taskReqVo).asResource()
            },
            onFailure = {
                _taskLiveData.value = Resource.Error(it)
            }, isShowLoading = taskReqVo.page != 1
        )

    }

    fun createTaskOrder(createTaskReqVo: CreateTaskReqVo) {
        launchOnUI(
            task = {
                _createTaskOrderLiveData.value = ginkgoRepository.createTaskOrder(createTaskReqVo).asResource()
            },
            onFailure = {
                _createTaskOrderLiveData.value = Resource.Error(it)
            }
        )
    }

}